package top.yzlin.dblock.component;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.yzlin.dblock.inter.StatementOperateEvent;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

@Component
public class JdbcConnectionOperate implements InitializingBean {
    private Map<String, Connection> connectionMap;
    private Map<String, DatabaseInfo> databaseInfoMap;


    @Autowired
    public void setDatabaseInfoMap(Map<String, DatabaseInfo> databaseInfoMap) {
        this.databaseInfoMap = databaseInfoMap;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        connectionMap = new HashMap<>(databaseInfoMap.size());
        databaseInfoMap.forEach((k, v) -> {
            try {
                Connection connection = DriverManager.getConnection(v.getJdbcUrl(), v.getUser(), v.getPassword());
                connectionMap.put(k, connection);
                connection.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });
    }

    public Connection getConnection(String dbName) {
        return connectionMap.get(dbName);
    }


    public void performStatement(StatementOperateEvent statementOperate) {
        Map<String, Statement> statementMap = new HashMap<>(connectionMap.size());
        connectionMap.forEach((k, v) -> {
            try {
                statementMap.put(k, v.createStatement());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });
        try {
            statementOperate.operate(statementMap);
            for (Map.Entry<String, Statement> entry : statementMap.entrySet()) {
                entry.getValue().close();
            }
            for (Map.Entry<String, Connection> entry : connectionMap.entrySet()) {
                entry.getValue().commit();
            }
        } catch (Exception e) {
            for (Map.Entry<String, Connection> entry : connectionMap.entrySet()) {
                try {
                    entry.getValue().rollback();
                } catch (SQLException ex) {
                    statementOperate.rollBackException(e, ex);
                }
            }
            statementOperate.operateException(e);
        }
    }


}
